package org.zerofwk.example.datastruct.queue;

/**
 * desc:
 *  循环数组：保留1个头空间
 * @author: Administrator
 * @date: 2021/4/28 13:44
 */
public class CircleArrayQueueTest {
    public static void main(String[] args) {
        CircleArray queue = new CircleArray(5);
        queue.add(3);
        queue.add(4);
        queue.add(5);
        queue.add(6);
        queue.add(7);
        queue.show();

        System.out.printf("取出元素：arr[%d]=%d\n", queue.front, queue.get());

        queue.add(7);
        queue.show();

        System.out.printf("取出元素：arr[%d]=%d\n", queue.front, queue.get());
        queue.add(10);
        queue.show();
    }

    static class CircleArray {
        private int maxSize;
        private int front;
        private int rear;
        private int arr[];

        private CircleArray(int pMaxSize) {
            maxSize = pMaxSize;
            front = 0;
            rear = 0;
            arr = new int[maxSize];
        }

        public boolean isFull() {
            return (rear + 1) % maxSize == front;
        }

        public boolean isEmpty() {
            return front == rear;
        }

        public void add(int pElem) {
            if (isFull()) {
                System.out.println("add()->数组已满，无法再添加: " + pElem);
                return;
            }
            arr[rear] = pElem;
            rear = (rear + 1) % maxSize;
        }

        public int get() {
            if (isEmpty()) {
                throw new RuntimeException("get()->数据已空。");
            }
            int curVal = arr[front];
            arr[front] = -1;
            front = (front + 1) % maxSize;
            return curVal;
        }

        public void show() {
            if (isEmpty()) {
                throw new RuntimeException("show()->数组是空的.");
            }

            for (int i = 0; i < maxSize; i++) {
                System.out.printf("arr[%d]=%d,", i, arr[i]);
            }
            System.out.println("");
        }

        public int size() {
            return (rear + maxSize - front) % maxSize;
        }
    }
}
